﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{

    public class LaserMarkingStationSelfInspectionConfirmationQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] LaserMarkingStationSelfInspectionConfirmationQuery LMSSICQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (LMSSICQ.PageNumber <= 0 || LMSSICQ.PageSize <= 0)
            {

                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (LMSSICQ.LMSSIC_ID != 0)
                    {
                        whereClause += " AND  LMSSCID = @ID";
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_OperatorName))
                    {
                        whereClause += " AND  LMSSCOperatorName LIKE @OperatorName";
                    }
                    if (LMSSICQ.LMSSIC_ConfirmationTime != default(DateTime))
                    {
                        whereClause += " AND  LMSSCConfirmationTime = @ConfirmationTime";
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_LineParting))
                    {
                        whereClause += " AND  LMSSCLineParting LIKE @LineParting";
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_ProductVSMarkingModel))
                    {
                        whereClause += " AND  LMSSCProductVSMarkingModel LIKE @ProductVSMarkingModel";
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_NonconformanceDescriptionIfAny))
                    {
                        whereClause += " AND  LMSSCNonconformanceDescriptionIfAny LIKE @NonconformanceDescriptionIfAny";
                    }

                    var query = $@"
                        SELECT 
                             LMSSCID,  LMSSCOperatorName,  LMSSCConfirmationTime,  LMSSCLineParting, 
                             LMSSCProductVSMarkingModel,  LMSSCNonconformanceDescriptionIfAny,LMSSCNonconformanceImage,LMSSCCreateCreator,LMSSCCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                 LMSSCID,  LMSSCOperatorName,  LMSSCConfirmationTime,  LMSSCLineParting, 
                                 LMSSCProductVSMarkingModel,  LMSSCNonconformanceDescriptionIfAny,LMSSCNonconformanceImage,LMSSCCreateCreator,LMSSCCreateTime,
                                ROW_NUMBER() OVER(ORDER BY  LMSSCID) AS RowNum
                             FROM LaserMarkingStationSelfInspectionConfirmation {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (LMSSICQ.PageNumber - 1) * LMSSICQ.PageSize + 1;
                    int endRow = LMSSICQ.PageNumber * LMSSICQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (LMSSICQ.LMSSIC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = LMSSICQ.LMSSIC_ID });
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_OperatorName))
                    {
                        parameters.Add(new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50) { Value = $"%{LMSSICQ.LMSSIC_OperatorName}%" });
                    }
                    if (LMSSICQ.LMSSIC_ConfirmationTime != default(DateTime))
                    {
                        parameters.Add(new SqlParameter("@ConfirmationTime", SqlDbType.DateTime) { Value = LMSSICQ.LMSSIC_ConfirmationTime });
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_LineParting))
                    {
                        parameters.Add(new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = $"%{LMSSICQ.LMSSIC_LineParting}%" });
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_ProductVSMarkingModel))
                    {
                        parameters.Add(new SqlParameter("@ProductVSMarkingModel", SqlDbType.NVarChar, 50) { Value = $"%{LMSSICQ.LMSSIC_ProductVSMarkingModel}%" });
                    }
                    if (!string.IsNullOrEmpty(LMSSICQ.LMSSIC_NonconformanceDescriptionIfAny))
                    {
                        parameters.Add(new SqlParameter("@NonconformanceDescriptionIfAny", SqlDbType.NVarChar, 100) { Value = $"%{LMSSICQ.LMSSIC_NonconformanceDescriptionIfAny}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var products = new List<LaserMarkingStationSelfInspectionConfirmation>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                products.Add(new LaserMarkingStationSelfInspectionConfirmation
                                {
                                    LMSSIC_ID = reader.GetInt32(reader.GetOrdinal("LMSSCID")),
                                    LMSSIC_OperatorName = reader.GetString(reader.GetOrdinal("LMSSCOperatorName")),
                                    LMSSIC_ConfirmationTime = reader.GetDateTime(reader.GetOrdinal("LMSSCConfirmationTime")),
                                    LMSSIC_LineParting = reader.GetString(reader.GetOrdinal("LMSSCLineParting")),
                                    LMSSIC_ProductVSMarkingModel = reader.GetString(reader.GetOrdinal("LMSSCProductVSMarkingModel")),
                                    LMSSIC_NonconformanceDescriptionIfAny = reader.GetString(reader.GetOrdinal("LMSSCNonconformanceDescriptionIfAny")),
                                    LMSSIC_NonconformanceImage = reader.GetString(reader.GetOrdinal("LMSSCNonconformanceImage")),
                                    LMSSC_CreateCreator = reader.GetString(reader.GetOrdinal("LMSSCCreateCreator")),
                                    LMSSC_CreateTime = reader.GetDateTime(reader.GetOrdinal("LMSSCCreateTime"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = LMSSICQ.PageNumber;
                            RO.PageSize = LMSSICQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
